<template>
  <div class="post-edit-container">
    <div class="edit-header">
      <h2>{{ getTitle }}</h2>
    </div>
    
    <div v-if="loading" class="loading-container">
      <a-spin />
    </div>
    
    <a-form
      v-else
      :model="formState"
      :rules="rules"
      ref="formRef"
      layout="vertical"
    >
      <a-form-item label="标题" name="title">
        <a-input 
          v-model:value="formState.title" 
          placeholder="请输入标题" 
          :maxlength="100"
          style="width: 100%"
          show-count
          allow-clear
        />
      </a-form-item>

      <a-form-item label="内容" name="content">
        <MarkdownEditor v-model:modelValue="formState.content" />
      </a-form-item>

      <a-form-item label="标签" name="tags">
        <a-select
          v-model:value="formState.tags"
          mode="multiple"
          placeholder="请选择或输入标签"
          :max-tag-count="10"
          :token-separators="[',']"
          style="width: 100%"
          allow-clear
          :options="filteredTagOptions"
          :filter-option="filterTags"
          show-search
          @search="handleSearch"
          @keydown.enter.prevent="handleEnterPress"
        >
          <template #dropdownRender="{ menuNode }">
            <div style="padding: 8px">
              <div style="font-size: 12px; color: #666; margin-bottom: 8px;">
                {{ searchValue ? '搜索结果：' : '热门标签：' }}
              </div>
              <div style="display: flex; flex-wrap: wrap; gap: 8px;">
                <template v-if="!searchValue">
                  <a-tag 
                    v-for="tag in commonStore.hotTagList" 
                    :key="tag"
                    style="cursor: pointer"
                    @click="handleTagClick(tag)"
                  >
                    {{ tag }}
                  </a-tag>
                </template>
                <template v-else>
                  <a-tag 
                    v-for="option in filteredTagOptions" 
                    :key="option.value"
                    style="cursor: pointer"
                    @click="handleTagClick(option.value)"
                  >
                    {{ option.label }}
                  </a-tag>
                  <div v-if="filteredTagOptions.length === 0" style="color: #999; padding: 4px 0;">
                    未找到相关标签
                  </div>
                </template>
              </div>
            </div>
          </template>
          <template #notFoundContent>
            <div style="padding: 8px; color: #999; text-align: center;">
              <!-- {{ searchValue ? '按回车创建新标签' : '输入关键词搜索标签' }} -->
              输入关键词搜索标签
            </div>
          </template>
        </a-select>
      </a-form-item>

      <a-form-item>
        <a-space>
          <a-button 
            type="primary" 
            :loading="submitting" 
            :disabled="submitting || !hasFormContent"
            @click="handleSubmit"
          >
            {{ formState.releaseFlag === 'Y' ? '保存' : '发布' }}
            
          </a-button>
          <a-button 
            :loading="submitting" 
            :disabled="submitting || !hasFormContent"
            @click="handleSaveDraft"
            v-if="!(formState.releaseFlag === 'Y')"
          >
            保存草稿
          </a-button>
          <a-button :disabled="submitting" @click="handleCancel">取消</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import MarkdownEditor from '@/components/MarkdownEditor/index.vue';
import { ref, onMounted, reactive, computed, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message, Modal } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import { userStore } from '@/store/modules/UserStore';
import { getDraft, postsDetails, publishPosts } from '@/api/front/social';
import { useCommonStore } from '@/store/modules/common';
import { debounce } from 'lodash-es';

const route = useRoute();
const router = useRouter();
const userstore = userStore();
const formRef = ref<FormInstance>();
const loading = ref(false);

// 公共数据
const commonStore = useCommonStore();

const formState = reactive({
  title: '',
  content: '',
  tags: [],
  postsId: '',
  releaseFlag: '',
  categoryId: 0
});

const isEdit = computed(() => !!route.query.postId);
const isNewPost = ref(false);

// 动态计算标题
const getTitle = computed(() => {
  if (isEdit.value) return '编辑帖子';
  if (isNewPost.value) return '发布新帖子';
  return '编辑草稿';
});

const rules = {
  title: [
    { required: true, message: '请输入标题' },
    { max: 100, message: '标题不能超过100个字符' }
  ],
  content: [{ required: true, message: '请输入内容' }],
};

const initDraft = async () => {
  loading.value = true;
  try {
    const res = await getDraft();
    if (res.data) {
      formState.title = res.data.title;
      formState.content = res.data.content;
      formState.tags = res.data.tags || [];
      formState.postsId = res.data.postId;
      formState.releaseFlag = 'N';
      formState.categoryId = res.data.categoryId;
    } else {
      // 没有草稿时，将状态设置为新帖子
      isNewPost.value = true;
      formState.title = '';
      formState.content = '';
      formState.tags = [];
      formState.postsId = '';
      formState.releaseFlag = 'N';
      formState.categoryId = 0;
    }
  } catch (error) {
    message.error('获取草稿失败');
    // 发生错误时也设置为新帖子状态
    isNewPost.value = true;
  } finally {
    loading.value = false;
  }
};

// 添加搜索值状态
const searchValue = ref('');

// 修改标签选项的计算属性
const tagOptions = computed(() => {
  return (commonStore.allTagList || []).map(tag => ({
    label: tag,
    value: tag
  }));
});

// 添加过滤后的标签选项计算属性
const filteredTagOptions = computed(() => {
  if (!searchValue.value) {
    return [];
  }
  return tagOptions.value.filter(option => 
    option.label.toLowerCase().includes(searchValue.value.toLowerCase())
  );
});

// 自定义过滤函数
const filterTags = (input: string, option: any) => {
  if (!input) {
    return false;
  }
  return option.label.toLowerCase().includes(input.toLowerCase());
};

// 添加搜索处理函数
const handleSearch = (value: string) => {
  searchValue.value = value;
};

// 修改标签点击处理函数
const handleTagClick = (tag: string) => {
  if (!formState.tags) {
    formState.tags = [];
  }
  if (!formState.tags.includes(tag)) {
    formState.tags = [...formState.tags, tag];
  }
  searchValue.value = '';  // 清空搜索值
};

// 修改回车处理函数
const handleEnterPress = () => {
  
  // 如果有搜索值且有过滤后的标签
  if (searchValue.value && filteredTagOptions.value.length > 0) {
    // 获取第一个标签
    const firstTag = filteredTagOptions.value[0].value;
    handleTagClick(firstTag);
    // 清除搜索值
    searchValue.value = '';
  }
};

// 获取帖子详情
const getPostsDetails = async (postsId: string) => {
  const res = await postsDetails(postsId);
  if (res.data) {
    formState.title = res.data.title;
    formState.content = res.data.content;
    formState.tags = res.data.tags || [];
    formState.postsId = res.data.postId;
    formState.releaseFlag = res.data.releaseFlag;
  }
};

onMounted(async () => {
  const postsId = route.query.postId as string;
  if (postsId) {
    await getPostsDetails(postsId);
  } else {
    await initDraft();
  }
  // 确保获标数据
  await commonStore.getCommonData();
});

// 使用单个 loading 状态替换原来的两个
const submitting = ref(false);

// 修改发布函数
const handleSubmit = debounce(async () => {
  if (submitting.value) return;  // 防止重复提交
  
  try {
    submitting.value = true;
    await formRef.value?.validate();
    
    // 调用发布接口
    await publishPosts({
      title: formState.title,
      content: formState.content,
      tags: formState.tags,
      releaseFlag: 'Y',
      postsId: formState.postsId,
      categoryId: formState.categoryId
    });
    
    message.success('发布成功');
    toUserPostsList();
  } catch (error) {
    if (error instanceof Error) {
      message.error('发布失败：' + error.message);
    } else {
      message.error('发布失败');
    }
    console.error('发布失败:', error);
  } finally {
    submitting.value = false;
  }
}, 500);

// 修改保存草稿函数
const handleSaveDraft = debounce(async () => {
  if (submitting.value) return;  // 防止重复提交
  
  try {
    submitting.value = true;
    
    //调用保存草稿接口
    await publishPosts({
      title: formState.title,
      content: formState.content,
      tags: formState.tags,
      releaseFlag: 'N',
      postsId: formState.postsId,
      categoryId: formState.categoryId
    });
    
    message.success('保存草稿成功');
    
    // 跳转到个人中心的个人数据页面，并传递 tab 和 type 参数
    toUserPostsList();
  } catch (error) {
    if (error instanceof Error) {
      message.error('保存失败：' + error.message);
    } else {
      message.error('保存失败');
    }
    console.error('保存草稿失败:', error);
  } finally {
    submitting.value = false;
  }
}, 500);

const toUserPostsList = () => {
  // 跳转到个人中心的个人数据页面，并传递 tab 和 type 参数
  router.push({
      path: '/user',
      query: {
        tab: 'userData',
        type: 'posts'  // 指定要激活的标签页
      }
    });
};

// 添加表单内容检查的计算属性
const hasFormContent = computed(() => {
  return !!(
    formState.title.trim() || // 标题不为空
    formState.content.trim() || // 内容不为空
    formState.tags.length > 0 // 有标签
  );
});

// 修改取消函数，使用 hasFormContent 判断
const handleCancel = debounce(() => {
  if (submitting.value) return;  // 如果正在提交，不允许取消
  
  // 使用 hasFormContent 判断是否有内容
  if (hasFormContent.value) {
    Modal.confirm({
      title: '确认离开？',
      content: '当前内容尚未保存，确定要离开吗？',
      onOk: () => {
        router.back();
      }
    });
  } else {
    router.back();
  }
}, 500);

// 组件卸载时清理防抖函数
onBeforeUnmount(() => {
  handleSubmit.cancel();
  handleSaveDraft.cancel();
  handleCancel.cancel();
});
</script>

<style lang="scss" scoped>
.post-edit-container {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  min-height: 400px;
  
  .edit-header {
    margin-bottom: 24px;
    
    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }
  }
  
  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
  }
}

// 添加标签相关样式
:deep(.ant-select-dropdown) {
  .ant-tag {
    margin: 0;
    transition: all 0.3s;
    padding: 2px 8px;
    display: inline-flex;
    align-items: center;

    &:hover {
      color: #1890ff;
      border-color: #1890ff;
      background: #e6f7ff;
    }
  }

  // 优化搜索结果样式
  .ant-select-item {
    padding: 8px 12px;
    
    &:hover {
      background-color: #f5f5f5;
    }
    
    &.ant-select-item-option-selected {
      background-color: #e6f7ff;
    }
  }
}

// 优化选择器样式
:deep(.ant-select) {
  .ant-select-selection-item {
    background: #f0f2f5;
    border-radius: 4px;
    margin: 2px;
  }

  .ant-select-selection-search {
    margin: 2px;
  }
}

// 添加字数统计样式
:deep(.ant-input-affix-wrapper) {
  .ant-input-show-count-suffix {
    color: #999;
  }
}

// 添加禁用按钮的样式
:deep(.ant-btn[disabled]) {
  cursor: not-allowed;
  
  &.ant-btn-primary {
    background-color: #f5f5f5;
    border-color: #d9d9d9;
    color: rgba(0, 0, 0, 0.25);
  }
}
</style>

